import AMapLoader from "@amap/amap-jsapi-loader";
import { Button, Modal, message } from "antd";
import React, { memo, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import AirBarEcharts from "./components/AirBarEcharts";
import AirPieECharts from "./components/AirPieECharts";
import TimelineController from "./components/DateController";
import HumiECharts from "./components/HumiECharts";
import Line from "./components/Line";
import TempECharts from "./components/TempECharts";
import EchartsLeft from "./EchartsLeft";
import EchartsRight from "./EchartsRight";
import bottomicon from "./images/bottomicon.png";
import corrode from "./images/corrode.png";
import corrodeing from "./images/corrodeing.png";
import dingwei from "./images/dingwei.png";
import leavl from "./images/leavl.png";
import lefticon from "./images/lefticon.png";
import righticon from "./images/righticon.png";
import searchLeft from "./images/searchLeft.png";
import searchicon from "./images/searchpng.png";
import searchRight from "./images/searchRight.png";
import titleicon from "./images/titleicon.png";
const LeftEchartsStyle = {
  width: "306px",
  height: "670px",
  backgroundColor: "rgba(2, 16, 25, 0.9)",
  top: "20px",
  left: "20px",
  zIndex: 100,
};
const RightEchartsStyle = {
  width: "306px",
  height: "670px",
  backgroundColor: "rgba(2, 16, 25, 0.9)",
  top: "20px",
  right: "20px",
  zIndex: 100,
};
const latlngStyle = {
  backgroundColor: "rgba(2, 16, 25, 0.9)",
  display: "flex",
  justifyContent: "space-between",
  position: "absolute",
  bottom: "10%",
  left: "20px",
  zIndex: 100,
  width: "306px",
  padding: "5px 20px",
  color: "#fff",
  fontSize: "14px",
};
const EchartsStyle = {
  position: "absolute",
  padding: "20px",
};

const searchBox = {
  position: "absolute",
  top: "5%",
  zIndex: 100,
  display: "flex",
};

const Lvavl = {
  position: "absolute",
  border: "1px solid #1b232e",
  bottom: "10%",
  right: "20px",
  zIndex: 100,
  width: "346px",
};
const inputBoxStyle = {
  display: "flex",
};
const inputStyle = {
  backgroundColor: "rgba(2, 16, 25, 0.9)",
  height: "36px",
  border: "none",
  width: "400px",
  color: "#fff",
  marginLeft: "10px",
  marginRight: "10px",
  fontSize:"16px"
};
// 添加全局样式或使用 styled-components
const CustomModalWrapper = styled.div`
  .ant-modal-content {
    box-shadow: none;
    padding: 20px;
    width: 380px;
    background-color: rgba(2, 16, 25, 0.9);
  }

  .ant-modal-close {
    color: #fff;
  }

  .ant-modal-body {
    padding: 0;
  }
  .amap-logo {
    display: none;
    opacity: 0 !important;
  }
`;
const MAPKYT = "cd6ee207dbb4b3d02a61760224976ed9";
const AMapHome = () => {
  const mapRef = useRef(null);
  const airData = useRef({});
  const [airDatajson, setAirDatajson] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [dataLoaded, setDataLoaded] = useState(false);
  const [address, setAddress] = useState({
    province: "",
    city: "",
    district: "",
  });
  const [latlng, setLatlng] = useState({ lat: "", lng: "" });
  const [AMapInstance, setAMapInstance] = useState(null);
  const [heatInstance, setHeatInstance] = useState(null);
  const [map, setMap] = useState(null);
  const [searchValue, setSearchValue] = useState("");
  const [heatData, setHeatData] = useState();
  const [playHeatData, setplayHeatData] = useState();
  const [heightVh, setHeightVh] = useState(false);
  const [showheat, setShowheat] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  useEffect(() => {
    const windowInnerWidth = window.innerWidth;
    const windowInnerHeight = window.innerHeight;
    console.log(windowInnerWidth, "windowInnerWidth", windowInnerHeight);
    if (windowInnerHeight === 1200) {
      setHeightVh(true);
    }
    const loadData = async () => {
      try {
        const response = await fetch("/data/airjson.json");
        const data = await response.json();
        // 178627数据
        const heatData = data.slice(170000).map((item) => ({
          lng: item.long,
          lat: item.lat,
          count: item.i * 10,
        }));
        // 初始地图
        console.log(heatData, "heatData");
        const Playdate = data.map((item) => ({
          lng: item.long,
          lat: item.lat,
          count: item.i * 10,
        }));
        setplayHeatData(Playdate);
        setHeatData(heatData);
        setAirDatajson(data);
        // 数据加载完成，设置状态
        setDataLoaded(true);
        // 同时更新 ref 以在回调中使用最新数据
      } catch (error) {
        console.error("加载数据失败:", error);
      }
    };
    loadData();
  }, []);
  useEffect(() => {
    if (dataLoaded) {
      AMapLoader.load({
        key: MAPKYT,
        version: "2.0",
        plugins: ["AMap.Geocoder", "AMap.HeatMap"],
        Loca: {
          version: "2.0.0",
        },
      })

        .then((AMap) => {
          const map = new AMap.Map(mapRef.current, {
            zoom: 5,
            center: [116.397428, 39.90923],
            mapStyle: "amap://styles/darkblue",
          });
          //初始化heatmap对象
          const heatmap = new AMap.HeatMap(map, {
            radius: 25, //给定半径
            opacity: [0, 0.8],
            gradient: {
              0.5: "blue",
              0.65: "rgb(117,211,248)",
              0.7: "rgb(0, 255, 0)",
              0.9: "#ffea00",
              1.0: "red",
            },
          });

          // heatmap.setDataSet({
          //   data: heatData,
          //   max: 100,
          // });
          setHeatInstance(heatmap);
          setAMapInstance(AMap);
          setMap(map);

          const clickHandler = async (e) => {
            const { lnglat } = e;
            setLatlng({
              lat: lnglat.lat,
              lng: lnglat.lng,
            });
            try {
              const addressComponent = await getprovinceCity(AMap, lnglat);
              console.log("获取地址成功", addressComponent);
              findlatlng(lnglat, airDatajson);
              showModal();
            } catch (error) {
              console.log(error, "error");
              message.warning(error.message);
            }
          };
          map.on("click", clickHandler);
        })
        .catch((e) => {
          console.error("地图加载失败:", e); // 添加错误日志
        });
    }
  }, [dataLoaded]); // 移除不必要的依赖

  /**
   * 根据经纬度获取省、市、区信息
   * @param {Object} AMap - 高德地图实例
   * @param {Object} lnglat - 经纬度对象
   */

  function getprovinceCity(AMap, lnglat) {
    return new Promise((resolve, reject) => {
      const getlnglat = [lnglat.lng, lnglat.lat];
      var geocoder = new AMap.Geocoder();
      // 根据坐标逆地理编码
      geocoder.getAddress(getlnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          const addressComponent = result?.regeocode?.addressComponent;
          const { province, city, district } = addressComponent;
          // 设置地址信息

          setAddress({
            province,
            city,
            district,
          });
          resolve(addressComponent);
        } else {
          // console.log("获取地址失败", result);
          reject(new Error("获取地址失败,不是中国境内"));
        }
      });
    });
  }

  // 定义一个函数来计算两点之间的欧几里得距离

  const calculateDistance = (lat1, lng1, lat2, lng2) => {
    return Math.sqrt(Math.pow(lat1 - lat2, 2) + Math.pow(lng1 - lng2, 2));
  };

  function findlatlng(evenlnglat, data) {
    console.log(evenlnglat, "evenlnglat");
    let minDistance = Infinity;
    let closestData = null;
    // 遍历数据数组
    for (let i = 0; i < data.length; i++) {
      const currentData = data[i];
      const distance = calculateDistance(
        evenlnglat.lat,
        evenlnglat.lng,
        currentData.lat,
        currentData.long
      );

      if (distance < minDistance) {
        minDistance = distance;
        closestData = currentData;
      }
    }
    airData.current = closestData;
  }

  const handleSearch = async () => {
    if (!searchValue || !AMapInstance) {
      message.warning("请输入搜索内容");
      return;
    }
    const geocoder = new AMapInstance.Geocoder();
    try {
      const result = await new Promise((resolve, reject) => {
        geocoder.getLocation(searchValue, (status, result) => {
          status === "complete"
            ? resolve(result)
            : reject(new Error("地址解析失败---"));
        });
      });
      const { location } = result.geocodes[0];
      map.setCenter([location.lng, location.lat]);
      map.setZoom(8);
      var marker = new AMapInstance.Marker({
        position: [location.lng, location.lat], // 标记位置
        icon: dingwei,
        map: map, // 将标记添加到地图上
      });
      map.add(marker);

      marker.on("click", function (e) {
        const { lnglat } = e;
        console.log(lnglat, "lnglat");
        setLatlng({
          lat: lnglat.lat,
          lng: lnglat.lng,
        });
        findlatlng(lnglat, airDatajson);
        getprovinceCity(AMapInstance, lnglat);
        showModal();
      });
    } catch (error) {
      message.error("搜索失败");
    }
  };
  const ChangeSource = (chunk) => {
    console.log(chunk, "chunk");
    heatInstance.show();
    heatInstance.setDataSet({
      data: chunk,
      max: 100,
    });
  };
  const corrodeStyle = {
    width: "160px",
    height: "40px",
    cursor: "pointer",
  };
  const handleCorrode = () => {
    setShowheat((prevShowheat) => !prevShowheat);
    console.log(showheat, "showheat");
    if (!showheat) {
      heatInstance.setDataSet({
        data: heatData,
        max: 100,
      });
      heatInstance.show();
    } else {
      heatInstance.hide();
    }
  };
  const ModalTitle = memo(() => {
    return (
      <div style={{ display: "flex", alignItems: "center" }}>
        <img
          src={titleicon}
          alt=""
          style={{ width: "12px", height: "12px", marginRight: "10px" }}
        />
        <div style={{ color: "#FFF" }}>
          {address.province}
          {address.city}
          {address.district}
        </div>
      </div>
    );
  });

  return (
    <div
      ref={mapRef}
      style={{
        width: "100%",
        height: heightVh ? "100vh" : "900px",
        display: "flex",
        justifyContent: "center",
      }}
    >
      <div style={searchBox}>
        <div style={inputBoxStyle}>
          <img src={searchLeft} alt="" style={{ height: "36px" }} />
          <input
            style={inputStyle}
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            placeholder="请输入地点名称或经纬度"
            className="search-input"
          />
          <img
            src={searchicon}
            alt=""
            style={{
              top: "15px",
              right: "300px",
              position: "absolute",
              width: "20px",
              height: "15px",
            }}
          />
          <img src={searchRight} alt="" style={{ height: "36px" }} />
        </div>

        <Button
          type="primary"
          onClick={handleSearch}
          style={{
            height: "36px",
            width: "72px",
            marginRight: "10px",
            marginLeft: "10px",
          }}
        >
          搜索
        </Button>

        <img
          src={showheat ? corrodeing : corrode}
          alt=""
          onClick={handleCorrode}
          style={corrodeStyle}
        />
      </div>
      <Modal
        open={isModalOpen}
        footer={null}
        onCancel={handleCancel}
        wrapClassName="custom-modal" // 添加自定义类名
        modalRender={(node) => <CustomModalWrapper>{node}</CustomModalWrapper>}
      >
        <div>
          <ModalTitle />
          <div style={{ display: "flex" }}>
            <AirPieECharts airData={airData.current} />
            <TempECharts temp={airData.current.temp} />
            <HumiECharts humi={airData.current.humi} />
          </div>
          <div>
            <AirBarEcharts airData={airData.current} />
          </div>
        </div>
      </Modal>

      <div style={{ ...LeftEchartsStyle, ...EchartsStyle }}>
        <EchartsLeft airData={airData.current} />
      </div>

      {isModalOpen && (
        <div style={{ ...RightEchartsStyle, ...EchartsStyle }}>
          <EchartsRight airData={airData.current} />
        </div>
      )}

      <div>
        <div style={Lvavl}>
          <img src={leavl} alt="" />
        </div>
      </div>
      <Line />
      <div style={latlngStyle}>
        <div>纬度: &nbsp; {latlng.lat || 39.90923}</div>
        <div>经度: &nbsp; {latlng.lng || 116.397428}</div>
      </div>
      <TimelineController
        playHeatData={playHeatData}
        ChangeSource={ChangeSource}
      />

      <img
        src={bottomicon}
        alt=""
        style={{
          position: "absolute",
          bottom: "35px",
          zIndex: 100,
        }}
      />

      <img
        src={lefticon}
        alt=""
        style={{
          position: "absolute",
          bottom: "100px",
          zIndex: 100,
          left: "5px",
        }}
      />
      <img
        src={righticon}
        alt=""
        style={{
          position: "absolute",
          bottom: "100px",
          zIndex: 100,
          right: "5px",
        }}
      />
    </div>
  );
};

export default AMapHome;
